/***
 * @description: 获取用户设备id 操作系统及版本 然后储存到本地
 * @param {*}
 * @return {*}
 */
import {ConfigStore} from '@/store/modules/config.js'
export function getDeviceUUID() {
	let deviceId = uni.getStorageSync('uni_deviceId') ||
		uni.getSystemInfoSync().deviceId ||
		uni.getSystemInfoSync().system + '_' + Math.random().toString(36).substr(2);
	// 获取设备id 跟操作系统名称及版本，如Android 10 然后存储起来
	uni.setStorageSync('uni_deviceId', deviceId)
	return deviceId;
}
// 禁止 pc端访问
export function prohibitDebug() {
	//平台、设备和操作系统 
	var system = {
		win: false,
		mac: false,
		xll: false
	};
	//检测平台
	var p = navigator.platform;
	system.win = p.indexOf("Win") == 0;
	system.mac = p.indexOf("Mac") == 0;
	system.x11 = (p == "X11") || (p.indexOf("Linux") == 0);
	if (system.win || system.mac || system.xll) {
		// window.location.href = "";
	}
	//禁止右键
	document.oncontextmenu = function(e) {
		return false
	}
	//禁止debug
	try {
		doCheck(0)
	} catch (err) {}
}
//截取小数
export function sliceNumber(num, dig) {
	if (typeof num === 'number') {
		num = String(num);
	}
	if (typeof dig === 'string') {
		dig = Number(dig);
	}
	if (num.includes('.')) {
		return Number(num.split('.')[0] + '.' + num.split('.')[1].slice(0, dig));
	} else {
		return Number(num);
	}
}

//随机数
export function randomStr() {
	let str = "qwertyu12345iopasdfgh67890jklzxcvbnm";
	let result = '';
	for (let i = 8; i > 0; --i) {
		result += str[Math.floor(Math.random() * str.length)];
	}
	return "0x" + result
}

/***
 * @description: 时间戳转日期加时分秒
 * @param {value} 时间戳
 * @author: white_queen
 */
export function formatDate(value) {
	if (value == null) {
		return '';
	} else {
		let date = new Date(value);
		let y = date.getFullYear(); // 年
		let MM = date.getMonth() + 1; // 月
		MM = MM < 10 ? ('0' + MM) : MM;
		let d = date.getDate(); // 日
		d = d < 10 ? ('0' + d) : d;
		let h = date.getHours(); // 时
		h = h < 10 ? ('0' + h) : h;
		let m = date.getMinutes(); // 分
		m = m < 10 ? ('0' + m) : m;
		let s = date.getSeconds(); // 秒
		s = s < 10 ? ('0' + s) : s;
		return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s;
	}
}
/***
 * @description: 时间戳转日期
 * @param {value} 时间戳
 * @author: white_queen
 */
export function formatDateDay(value) {
	if (value == null) {
		return '';
	} else {
		let date = new Date(value);
		let y = date.getFullYear(); // 年
		let MM = date.getMonth() + 1; // 月
		MM = MM < 10 ? ('0' + MM) : MM;
		let d = date.getDate(); // 日
		d = d < 10 ? ('0' + d) : d;
		return y + '-' + MM + '-' + d;
	}
}

/***
 * @description: 时间戳转日期
 * @param {value} 时间戳
 * @author: white_queen
 */
export function formatDateObj(value) {
	if (value == null) {
		return '';
	} else {
		let date = new Date(value);
		let y = date.getFullYear(); // 年
		let MM = date.getMonth() + 1; // 月
		MM = MM < 10 ? ('0' + MM) : MM;
		let d = date.getDate(); // 日
		d = d < 10 ? ('0' + d) : d;
		return {
			date: y + '-' + MM,
			day: d,
			week: "日一二三四五六".charAt(new Date().getDay())
		};
	}
}

/***
 * @description: 把时间戳转换成天数
 * @param {value} 时间戳
 * @author: white_queen
 */
export function formatTime(value) {
	let s = value - parseInt(Date.now() / 1000)
	let m = parseInt(s / 60)
	let h = parseInt(s / 60 / 60)
	if (h >= 1) {
		return h + '小时'
	} else {
		return m + '分钟'
	}
}
/***
 * @description: 把时间戳转换成天数
 * @param {dateTimeStamp} 时间戳
 * @author: white_queen
 */
export function getDateDiff(dateTimeStamp) {
	var minute = 1000 * 60;
	let hour = minute * 60;
	let day = hour * 24;
	let halfamonth = day * 15;
	let month = day * 30;
	let now = new Date().getTime();
	let diffValue = now - dateTimeStamp;
	if (diffValue < 0) { return; }
	let monthC = diffValue / month;
	let weekC = diffValue / (7 * day);
	let dayC = diffValue / day;
	let hourC = diffValue / hour;
	let minC = diffValue / minute;
	let result = "";
	if (monthC >= 1) {
		result = "" + parseInt(monthC) + "月前";
	} else if (weekC >= 1) {
		result = "" + parseInt(weekC) + "周前";
	} else if (dayC >= 1) {
		result = "" + parseInt(dayC) + "天前";
	} else if (hourC >= 1) {
		result = "" + parseInt(hourC) + "小时前";
	} else if (minC >= 1) {
		result = "" + parseInt(minC) + "分钟前";
	} else
		result = "刚刚";
	return result;
}
/***
 * @description: 把时间戳转换为过期时间
 * @param {dateTimeStamp} 时间戳
 * @author: white_queen
 */
export function getDateDiffEnd(dateTimeStamp) {
	var minute = 1000 * 60;
	let hour = minute * 60;
	let day = hour * 24;
	let halfamonth = day * 15;
	let month = day * 30;
	let now = new Date().getTime();
	let diffValue = dateTimeStamp - now;
	if (diffValue < 0) { return; }
	let monthC = diffValue / month;
	let weekC = diffValue / (7 * day);
	let dayC = diffValue / day;
	let hourC = diffValue / hour;
	let minC = diffValue / minute;
	let result = "";
	if (monthC >= 1) {
		result = "" + parseInt(monthC) + "月后";
	} else if (weekC >= 1) {
		result = "" + parseInt(weekC) + "周后";
	} else if (dayC >= 1) {
		result = "" + parseInt(dayC) + "天后";
	} else if (hourC >= 1) {
		result = "" + parseInt(hourC) + "小时后";
	} else if (minC >= 1) {
		result = "" + parseInt(minC) + "分钟后";
	} else
		result = "即将";
	return result;
}
/***
 * @description: 替换手机号4位*
 * @param {*}
 * @return {*}
 * @author: white_queen
 */
export function maskPhoneNumber(phoneNumber) {
	phoneNumber = String(phoneNumber)
	if (phoneNumber.length !== 11) {
		throw new Error('Invalid phone number format');
	}

	const maskedNumber = phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
	return maskedNumber;
}

// 识别二维码
export function parseCode(data) {
	uni.downloadFile({
		url: data,
		success: (res) => {
			if (res.statusCode === 200) {
				// #ifdef APP-PLUS
				plus.barcode.scan(res.tempFilePath, (type, res) => {
					uni.hideLoading()
					if (type == 0) {
						plus.runtime.openURL(res)
					}else{
						uni.fui.toast('未识别到二维码')
					}
				}, (e) => {
					uni.hideLoading()
					if (e.code == 3) {
						uni.fui.toast('未识别到二维码')
					} else {
						uni.fui.toast('无法识别此图片')
					}
				})
				// #endif
			}
		}
	})
}

/***
 * @description: 根据日期生成全局28位唯一订单号
 * @param {*}
 * @return {*}
 * @author: white_queen
 */
export function generate28DigitOrderId() {
	const currentDate = new Date();
	const year = currentDate.getFullYear();
	const month = String(currentDate.getMonth() + 1).padStart(2, '0');
	const day = String(currentDate.getDate()).padStart(2, '0');

	const hours = String(currentDate.getHours()).padStart(2, '0');
	const minutes = String(currentDate.getMinutes()).padStart(2, '0');
	const seconds = String(currentDate.getSeconds()).padStart(2, '0');

	const randomPart1 = String(Math.floor(Math.random() * 1000)).padStart(3, '0');
	const randomPart2 = String(Math.floor(Math.random() * 1000000)).padStart(6, '0');
	const randomPart3 = String(Math.floor(Math.random() * 1000000)).padStart(6, '0');

	const orderId = `${year}${month}${day}${hours}${minutes}${seconds}${randomPart1}${randomPart2}${randomPart3}`;

	return orderId;
}

/***
 * @description: img回显格式转换
 * @param {*}
 * @return {*}
 * @author: white_queen
 */
export function replaceImg(url) {
	let arr = []
	if (Array.isArray(url)) {
		url.forEach(vm => {
			arr.push({ 'url': vm })
		})
	} else {
		arr.push({ 'url': url })
	}
	return arr
}

// 防抖函数
export function debounce(func, delay) {
	let timer;
	return function(...args) {
		clearTimeout(timer);
		timer = setTimeout(() => {
			func.apply(this, args);
		}, delay);
	};
}
/***
 * @description: 判断数组 或者对象是否为空
 * @param {*}
 * @return {*}
 * @author: white_queen
 */
export function isEmpty(obj) {
	if (Array.isArray(obj)) {
		return obj.length === 0;
	}

	if (typeof obj === 'object' && obj !== null) {
		return Object.keys(obj).length === 0;
	}

	return true; // 如果不是数组也不是对象，认为是空的
}

/***
 * @description: 把分单位转义成元
 * @param {inputObj} 对象
 * @return {fieldsToConvert}需要转义的字段
 * @author: white_queen
 */
export function convertAmountToYuan(inputObj, fieldsToConvert) {
	// 复制输入对象，以免修改原对象
	const resultObj = { ...inputObj };
	// 遍历字段并将其除以 100
	fieldsToConvert.forEach(field => {
		if (resultObj.hasOwnProperty(field)) {
			resultObj[field] = resultObj[field] / 100;
		}
	});
	return resultObj;
}
/***
 * @description: 计算打折费用
 * @param {*}  discount 用户折扣  num:总金额
 * @return {*}
 * @author: white_queen
 */

export function setDiscount(discount, num) {
	//判断是否全场打折
	if(ConfigStore().config.isDiscount){
		return Number(num) * (Number(ConfigStore().config.discountPrice) / 100)
	}else{
		return Number(num) * (Number(discount) / 100)
	}
}
/***
 * @description: 检测字符串中包含链接的字符并加 a链接
 * @param {*}  discount 
 * @return {*}
 * @author: white_queen
 */
export function getHref(content) {
	if (!content) {
		return "";
	}
	let urlPattern = /(https?:\/\/|www\.)[a-zA-Z_0-9\-@]+(\.\w[a-zA-Z_0-9\-:]+)+(\/[\(\)~#&\-=?\+\%/\.\w]+)?/g;
	content = content.replace(urlPattern, function(match) {
		var href = match;
		if (match.indexOf("http") == -1) {
			href = "http://" + match;
		}
		return "<a target=\"_blank\" href=\"" + href + "\">" + match + "</a>";
	});
	return content;
}


           

